package org.dromara.web.appInterface;

import cn.dev33.satoken.annotation.SaIgnore;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.dromara.app.appParams.*;
import org.dromara.app.appReturn.*;
import org.dromara.app.config.AppUserActivityConfig;
import org.dromara.app.cssUtils.CssExceptionDescription;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.domain.*;
import org.dromara.app.domain.vo.SkNickHeadVo;
import org.dromara.app.service.*;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.params.AppTypeName;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.system.service.ISysConfigService;
import org.dromara.web.CssUtil.CssOrderPaySever;
import org.dromara.web.CssUtil.CssOrderServer;
import org.dromara.web.CssUtil.WxPayBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Tag(name = "首页相关接口")
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/home")
@SaIgnore
public class AppHomeInterface {
    private final ISkYueJuService iSkYueJuService;
    private final ISkShopService iSkShopService;
    private final ISkAppUserService iSkAppUserService;
    private final ISkVipPriceService iSkVipPriceService;
    private final ISkDaRenApplyService iSkDaRenApplyService;
    private final ISkYueJuDemoService iSkYueJuDemoService;
    private final ISkDailiShengqingService iSkDailiShengqingService;
    private final CssOrderServer cssOrderServer;
    private final ISkMembershipOrderService iSkMembershipOrderService;
    private final ISkDarenBrowsingHistoryService iSkDarenBrowsingHistoryService;
    private final ISkReportService iSkReportService;
    private final ISkYueJuTypeService iSkYueJuTypeService;
    private final ISkNickHeadService iSkNickHeadService;
    private final ISysConfigService iSysConfigService;
    private final CssOrderPaySever cssOrderPaySever;
    private final ISkYueDanOrderService iSkYueDanOrderService;
    private final ISkYueDanOrderLogService iSkYueDanOrderLogService;
    private final IBfAppUserActivityService iBfAppUserActivityService;

    @Autowired
    WxPayBean wxPayBean;


    /**
     * 更新用户位置
     */
    @PostMapping("/updateAddress")
    @Operation(summary = "更新用户位置", method = "post")
    public R updateAddress(@RequestBody UpdateAddressParams updateAddressParams, HttpServletRequest req){
        iSkAppUserService.updateAddress(updateAddressParams,req);
        //添加活跃度
        iBfAppUserActivityService.addActivity(CssUtils.getUserId(req), AppUserActivityConfig.JOIN_YUE_JU);
        return R.ok("请求成功");
    }

    /**
     * 星球在线用户列表
     */
    @PostMapping("/getOnlineUserList")
    @Operation(summary = "星球在线用户列表", method = "post")
    public R<List<AppXingQiuParams>> getOnlineUserList(HttpServletRequest req){
        List<AppXingQiuParams> list = iSkAppUserService.getOnlineUserList(req);
        return R.ok(list);
    }

    /**
     * 会员中心
     */
    @PostMapping("/getMemberCenter")
    @Operation(summary = "会员中心", method = "post")
    public R<List<AppMemberCenterReturn>> getMemberCenter(HttpServletRequest req){
        List<AppMemberCenterReturn> list = iSkVipPriceService.getMemberCenter(req);
        return R.ok(list);
    }

    /**
     * 首页筛选达人信息
     */
    @PostMapping("/getFilteringExpertInformation")
    @Operation(summary = "首页筛选达人信息", method = "post")
    public R<List<AppDaRenInfo>> getFilteringExpertInformation(@RequestBody AppFilteringParams app, HttpServletRequest req){
        List<AppDaRenInfo> list = iSkAppUserService.getFilteringExpertInformation(app,req);
        return R.ok(list);
    }

    /**
     * 灵魂达人匹配 Soul Master Matching
     */
    @PostMapping("/getSoulMasterMatching")
    @Operation(summary = "灵魂达人匹配", method = "post")
    public R<AppYueJuListReturn> getSoulMasterMatching(@RequestBody AppTongYongParams app, HttpServletRequest req){
        AppYueJuListReturn apps = iSkYueJuService.getSoulMasterMatching(app,req);
        return R.ok(apps);
    }


    /**
     * 约局模版
     */
    @PostMapping("/getYueJuDemoList")
    @Operation(summary = "约局模版", method = "post")
    public R<List<AppMoBanReturn>> getYueJuDemoList(HttpServletRequest req){
            List<AppMoBanReturn> list = iSkYueJuDemoService.getYueJuDemoList(req);
        return R.ok(list);
    }


    /**
     * 发布约局
     */
    @PostMapping("/publishContract")
    @Operation(summary = "发布约局", method = "post")
    public R publishContract(@RequestBody AppFaBuYueJuParams app, HttpServletRequest req){
        //查询是否直接发布
        String config = iSysConfigService.selectConfigByKey("yue_ju_zi_dong_sheng_he");
        if (config!=null && config.equals("true")){
            app.setState("1");
        }else{
            app.setState("2");
        }
        SkYueJu model = iSkYueJuService.publishContract(app,req);
        //添加活跃度
        iBfAppUserActivityService.addActivity(model.getUserId(), AppUserActivityConfig.PUBLISH_YUE_JU);
        return R.ok(model);
    }

    /**
     * 尚科主流Party列表
     */
    @PostMapping("/getMainstreamParty")
    @Operation(summary = "尚科主流Party列表", method = "post")
    public R<List<AppMainstreamPartyReturn>> getMainstreamParty(@RequestBody AppTuiJianParams params, HttpServletRequest req){
        List<AppMainstreamPartyReturn> list = iSkShopService.getMainstreamParty(params,req);
        return R.ok(list);
    }

    /**
     * 集市列表
     */
    @PostMapping("/getJiShiList")
    @Operation(summary = "集市列表", method = "post")
    public R<List<AppMainstreamPartyReturn>> getJiShiList(@RequestBody AppTuiJianParams params, HttpServletRequest req){
        List<AppMainstreamPartyReturn> list = iSkShopService.getJiShiList(params,req);
        return R.ok(list);
    }

    /**
     * 商家详情
     */
    @PostMapping("/getShopInfo")
    @Operation(summary = "商家详情", method = "post")
    public R<AppMainstreamPartyReturn> getShopInfo(@RequestBody AppDetailByIdParams params, HttpServletRequest req){
        AppMainstreamPartyReturn app = iSkShopService.getShopInfo(params,req);
        return R.ok(app);
    }

    /**
     * 商家标签下约局列表
     */
    @PostMapping("/getShopYueJuList")
    @Operation(summary = "商家标签下约局列表", method = "post")
    public R<List<AppShopYueJuReturn>> getShopYueJuList(@RequestBody AppDetailByIdParams params, HttpServletRequest req){
        List<AppShopYueJuReturn> app = iSkYueJuService.getShopYueJuList(params,req);
        return R.ok(app);
    }

    /**
     * 推荐列表
     */
    @PostMapping("/recommendList")
    @Operation(summary = "推荐列表", method = "post")
    public R<List<AppYueJuListReturn>> recommendList(@RequestBody AppTuiJianParams params, HttpServletRequest req){
        List<AppYueJuListReturn> list = iSkYueJuService.recommendList(params,req);
        return R.ok(list);
    }

    /**
     * 派对大厅
     *
     * @param params
     * @param req
     * @return
     */
    @PostMapping("/partyHall")
    @Operation(summary = "派对大厅", method = "post")
    public R<List<AppYueJuListReturn>> partyHall(@RequestBody AppTuiJianParams params, HttpServletRequest req){
        List<AppYueJuListReturn> list = iSkYueJuService.partyHall(params,req);
        return R.ok(list);
    }

    /**
     * 派对大厅类型列表
     *
     * @param req
     * @return
     */
    @PostMapping("/partyHallType")
    @Operation(summary = "派对大厅类型列表", method = "post")
    public R<List<AppTypeName>> partyHallType(HttpServletRequest req){
//        List<AppTypeName> list = iSysDictTypeService.partyHallType(req);
        List<AppTypeName> list = iSkYueJuTypeService.getList(req);
        return R.ok(list);
    }

    /**
     * 约局类目列表
     *
     * @param req
     * @return
     */
    @PostMapping("/getYueJuTypeList")
    @Operation(summary = "约局类目列表", method = "post")
    public R<List<AppTypeName>> getYueJuTypeList(HttpServletRequest req){
//        List<AppTypeName> list = iSysDictTypeService.getYueJuTypeList(req);
        List<AppTypeName> list = iSkYueJuTypeService.getAllList(req);
        return R.ok(list);
    }

    /**
     * 甄选搭子信息
     */
    @PostMapping("/getSelectedOutfits")
    @Operation(summary = "甄选搭子信息", method = "post")
    public R<List<AppDaRenInfo>> getSelectedOutfits(@RequestBody AppTuiJianParams params, HttpServletRequest req){
        List<AppDaRenInfo> list = iSkDaRenApplyService.getSelectedOutfits(params,req);
        return R.ok(list);
    }

    /**
     * 代理申请
     */
    @PostMapping("/proxyApplication")
    @Operation(summary = "代理申请", method = "post")
    public R proxyApplication(@RequestBody AppDaiLiInfoParams params, HttpServletRequest req){
        iSkDailiShengqingService.proxyApplication(params,req);
        return R.ok("已提交申请");
    }


    /**
     * 达人申请
     */
    @PostMapping("/daRenApplication")
    @Operation(summary = "达人申请", method = "post")
    @RepeatSubmit()
    public R daRenApplication(@RequestBody AppDaRenParams params, HttpServletRequest req) throws TencentCloudSDKException {
        if (params.getBirthday()==null || params.getBirthday().equals("")){
            throw new RuntimeException("请填写生日");
        }
        String regex = "\\d{4}-\\d{2}";
        if (!params.getBirthday().matches(regex)){
            throw new RuntimeException("生日格式不正确");
        }
        iSkDaRenApplyService.daRenApplication(params,req);
        return R.ok("已提交申请");
    }


    /**
     * 达人热力图（在线用户）
     */
    @PostMapping("/getTalentHeatList")
    @Operation(summary = "达人热力图（在线用户）", method = "post")
    public R<List<AppTalentHeatReturn>> getTalentHeatList( HttpServletRequest req){
        List<AppTalentHeatReturn> list = iSkAppUserService.getTalentHeatList(req);
        return R.ok(list);
    }

    /**
     * 排行榜
     */
    @PostMapping("/getrankingList")
    @Operation(summary = "排行榜", method = "post")
    public R<List<AppRangingReturn>> getrankingList(@RequestBody AppRangintTypeParams params, HttpServletRequest req){
        List<AppRangingReturn> list = iSkAppUserService.getrankingList(params,req);
        return R.ok(list);
    }

    /**
     * 开通会员
     */
    @PostMapping("/openMembership")
    @Operation(summary = "开通会员", method = "post")
    public R openMembership(@RequestBody AppVipTypeParams params, HttpServletRequest req){
        try {
            SkAppUser skAppUser = iSkAppUserService.getUserById(CssUtils.getUserId(req));
            SkVipPrice price = iSkAppUserService.openMembership(skAppUser,params,req);
            //生成订单数据
            SkMembershipOrder skMembershipOrder = iSkMembershipOrderService.createOrder(price,skAppUser,params);
            if (params.getPayType().longValue()==1){
                if (skAppUser.getPrice().compareTo(price.getPrice())<0){
                    CssExceptionDescription.errorMsg(10014);
                }
                //增加余额操作记录 扣除余额
                cssOrderServer.activevipAccount(skAppUser,price,5L,"开通会员");
                //会员开通成功，更新订单状态和用户状态
                iSkMembershipOrderService.updateByInfo(skMembershipOrder);
                //开会员佣金计算
                cssOrderServer.memberDistributionCommission(skMembershipOrder);
                return R.ok("请求成功");
            }else{
                //微信支付
                String json = cssOrderPaySever.appVipPay(req,skMembershipOrder);
                return R.ok("请求成功",json);
            }
        }catch (RuntimeException e){
            throw new RuntimeException(e.getMessage());
        }

    }
    /**
     * 支付成功回调
     * @param req
     * @return
     */
    @PostMapping("/paymentCallback")
    @Operation(summary = "支付成功回调", method = "post")
    public String paymentCallback(HttpServletRequest req) {
        try {
            Map<String,String> map = cssOrderPaySever.callback(req);
            System.out.println("支付成功回调:"+map);
            WxPayApiConfig wxPayApiConfig = getApiConfig();
            WxPayApiConfigKit.putApiConfig(wxPayApiConfig);
            String returnCode = map.get("return_code");
            boolean verifyNotify = WxPayKit.verifyNotify(map, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256);
            System.out.println("verifyNotify:"+verifyNotify);
            if (verifyNotify) {
                System.out.println("returnCode:"+returnCode);
                System.out.println("WxPayKit.codeIsOk(returnCode):"+WxPayKit.codeIsOk(returnCode));
                if (WxPayKit.codeIsOk(returnCode)) {
                    String outTradeNo = map.get("out_trade_no");
                    SkMembershipOrder skMembershipOrder = iSkMembershipOrderService.getOrderById(outTradeNo.split("-")[1]);
                    if (skMembershipOrder.getPayState().longValue()==1){
                        return "success";
                    }
                    //会员开通成功，更新订单状态和用户状态
                    String wxTransactionId = map.get("transaction_id");
                    skMembershipOrder.setPayOrderSn(wxTransactionId);
                    iSkMembershipOrderService.updateByInfo(skMembershipOrder);
                    //开会员佣金计算
                    cssOrderServer.memberDistributionCommission(skMembershipOrder);
                }
            }
            return "fail";
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 首页小头像和数量
     */
    @PostMapping("/homePageImageNumber")
    @Operation(summary = "首页小头像和数量", method = "post")
    public R<Map<String,Object>> homePageImageNumber(HttpServletRequest req){
        Map<String,Object> map = iSkAppUserService.homePageImageNumber(req);
        return R.ok(map);
    }


    /**
     * 一键清除浏览记录
     */
    @PostMapping("/clearBrowsingHistory")
    @Operation(summary = "一键清除浏览记录", method = "post")
    public R clearBrowsingHistory(HttpServletRequest req){
        Long userId = CssUtils.getUserId(req);
        iSkDarenBrowsingHistoryService.clearBrowsingHistory(userId);
        return R.ok("操作成功");
    }

    /**
     * 举报
     */
    @PostMapping("/putReport")
    @Operation(summary = "举报", method = "post")
    public R putReport(@RequestBody AppReportParams params, HttpServletRequest req){
        Long userId = CssUtils.getUserId(req);
        iSkReportService.putReport(userId,params);
        return R.ok("举报成功");
    }

    /**
     * 获取随机用户名
     */
    @PostMapping("/getSjNickName")
    @Operation(summary = "获取随机用户名", method = "post")
    public R<SkNickHeadVo> getSjNickName(HttpServletRequest req){
        SkNickHeadVo vo = iSkNickHeadService.getSjNickName();
        return R.ok(vo);
    }

    //组装数据
    public WxPayApiConfig getApiConfig(){
        WxPayApiConfig apiConfig;

        try {
            apiConfig = WxPayApiConfigKit.getApiConfig(wxPayBean.getAppId());
        } catch (Exception e) {
            apiConfig = WxPayApiConfig.builder()
                .appId(wxPayBean.getAppId())
                .mchId(wxPayBean.getMchId())
                .partnerKey(wxPayBean.getPartnerKey())
                .certPath(wxPayBean.getCertPath())
                .domain(wxPayBean.getDomain())
                .build();
        }
        return apiConfig;
    }

//    /**
//     * 微信退款
//     */
//    @RequestMapping(value = "/refund", method = {RequestMethod.POST, RequestMethod.GET})
//    @Operation(summary = "微信退款", method = "post")
//    public String refund(@RequestParam(value = "transactionId", required = false) String transactionId,
//                         @RequestParam(value = "outTradeNo", required = false) String outTradeNo) {
//        try {
//            cssOrderPaySever.refund(transactionId,outTradeNo);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 退款通知
     */
    @RequestMapping(value = "/refundNotify", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String refundNotify(HttpServletRequest request) throws IOException {
        Map<String, String> params = cssOrderPaySever.callback(request);
        System.out.println("params:"+params);
        String returnCode = params.get("return_code");
        System.out.println("returnCode:"+returnCode);
        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        if (WxPayKit.codeIsOk(returnCode)) {
            WxPayApiConfig wxPayApiConfig = getApiConfig();
            WxPayApiConfigKit.putApiConfig(wxPayApiConfig);
            String reqInfo = params.get("req_info");
            String decryptData = WxPayKit.decryptData(reqInfo, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey());
            // 更新订单信息
            Map<String, String> result = WxPayKit.xmlToMap(decryptData);
            System.out.println(result);
            System.out.println("out_refund_no:"+result.get("out_refund_no"));
            System.out.println("refund_id:"+result.get("refund_id"));
            SkYueDanOrder order = iSkYueDanOrderService.getOrderById(result.get("out_refund_no").split("-")[1]);
            order.setState(3L);
            order.setRefundOtherOrder(result.get("refund_id"));
            iSkYueDanOrderService.updateByInfo(order);
            //类型 1:创建  2：转发  3：待接单  4：已接单  5：取消  6：完成
            iSkYueDanOrderLogService.createLog(order, "用户自主取消订单", 5L);
            // 发送通知等
            Map<String, String> xml = new HashMap<String, String>(2);
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            System.out.println("decryptData:"+decryptData);
            System.out.println("xml:"+xml);
            return WxPayKit.toXml(xml);
        }
        return null;
    }

}
